package com.cskaoyan.market.service;

import com.cskaoyan.market.db.domain.MarketFeedback;
import com.cskaoyan.market.db.domain.MarketUser;
import com.cskaoyan.market.db.domain.MarketUserExample;
import com.cskaoyan.market.db.mapper.MarketFeedbackMapper;
import com.cskaoyan.market.db.mapper.MarketUserMapper;
import com.cskaoyan.market.util.ResponseUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.regex.Pattern;

@Service
public class WxFeedbackServiceImpl implements WxFeedbackService {
    @Autowired
    MarketFeedbackMapper marketFeedbackMapper;
    @Autowired
    SecurityManager securityManager;
    @Autowired
    MarketUserMapper marketUserMapper;
    @Override
    @Transactional
    public Object submit(MarketFeedback marketFeedback) {
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        MarketUser user = (MarketUser) session.getAttribute("user");
        MarketUserExample marketUserExample = new MarketUserExample();
        MarketUserExample.Criteria userExampleCriteria = marketUserExample.createCriteria();
        userExampleCriteria.andUsernameEqualTo(user.getUsername());
        MarketUser marketUser = marketUserMapper.selectByExample(marketUserExample).get(0);
        Integer userId = marketUser.getId();
        String name=marketUser.getUsername();
        marketFeedback.setUserId(userId);
        marketFeedback.setAddTime(LocalDateTime.now());
        marketFeedback.setUpdateTime(LocalDateTime.now());
        marketFeedback.setUsername(name);
        String s=marketFeedback.getFeedType();
        String tel=marketFeedback.getMobile();
        if(StringUtils.isEmpty(s)){
            return ResponseUtil.fail(106,"请选择反馈类型");
        }
        if (StringUtils.isBlank(tel)||tel.isEmpty()) {
            return ResponseUtil.fail(104,"请输入11位电话号码");
        }
        while (Pattern.matches("^1[1-9]\\d{9}$", tel)) {
            marketFeedbackMapper.insertSelective(marketFeedback);
            return ResponseUtil.ok();
        }
        return ResponseUtil.fail(401,"参数错误");
    }

}
